package com.liyasong.cf.movie;

import java.util.List;

import org.apache.mahout.cf.taste.impl.neighborhood.NearestNUserNeighborhood;
import org.apache.mahout.cf.taste.impl.recommender.CachingRecommender;
import org.apache.mahout.cf.taste.impl.recommender.GenericUserBasedRecommender;
import org.apache.mahout.cf.taste.impl.similarity.PearsonCorrelationSimilarity;
import org.apache.mahout.cf.taste.model.DataModel;
import org.apache.mahout.cf.taste.neighborhood.UserNeighborhood;
import org.apache.mahout.cf.taste.recommender.RecommendedItem;
import org.apache.mahout.cf.taste.recommender.Recommender;
import org.apache.mahout.cf.taste.similarity.UserSimilarity;

import com.liyasong.cf.MyDataModel;
import com.liyasong.cf.MysqlJdbc;

/**
 * Hello world!
 *
 */
public class GenericRecommender 
{
    public static void main( String[] args ) throws Exception
    {
        System.out.println("标准数据集电影推荐：");
        System.out.println("算法选择：基于用户的协同过滤，最邻近邻居个数设为3个");
    	long start = System.currentTimeMillis();
        
        DataModel dataModel = MyDataModel.MovieData();//ope_time=6527ms
        long dataEnd = System.currentTimeMillis();
        System.out.println("用户数:"+dataModel.getNumUsers()+" 电影数:"+dataModel.getNumItems());
        System.out.println("用户id为1024的用户的评分记录：");
//        System.out.println(dataModel.getPreferencesFromUser(1024));
        MysqlJdbc mj = new MysqlJdbc();
        for (String string : mj.getUserRecord(dataModel, 1024)) {
			System.out.println(string);
		}

        UserSimilarity userSimilarity = new PearsonCorrelationSimilarity(dataModel);
        long similarityEnd = System.currentTimeMillis();
        UserNeighborhood userNeighborhood = new NearestNUserNeighborhood(3, userSimilarity, dataModel);
        long neighborEnd = System.currentTimeMillis();
        Recommender recommender = new GenericUserBasedRecommender(dataModel, userNeighborhood, userSimilarity);
        
        Recommender cachingRecommender = new CachingRecommender(recommender);
        long recommenderEnd = System.currentTimeMillis();
        List<RecommendedItem> recommendations = cachingRecommender.recommend(1024, 8);
        long recommendEnd = System.currentTimeMillis();
        System.out.println("对用户id为1024的用户的电影推荐（8部）：");
//        System.out.println(recommendations);
        for (String str : mj.getRecommendInfo(recommendations)) {
			System.out.println(str);
		}
        
//        long end = System.currentTimeMillis();
        System.out.println("程序运行时间(dataModel):"+(dataEnd-start)+"ms");
        System.out.println("程序运行时间(userSimilariry):"+(similarityEnd-dataEnd)+"ms");
        System.out.println("程序运行时间(neighborhood):"+(neighborEnd-similarityEnd)+"ms");
        System.out.println("程序运行时间(recommender):"+(recommenderEnd-neighborEnd)+"ms");
        System.out.println("程序运行时间(recommend,只对1024用户生成推荐):"+(recommendEnd-recommenderEnd)+"ms");
        
    }
}
